<template>
	<div class="vk-data-goods-sku-popup" :class="valueCom && complete ? 'show' : 'none'">
		<div class="mask" @click="close('mask')"></div>
		<div class="layer" :style="{ borderRadius: borderRadius + 'px ' + borderRadius + 'px 0 0' }">
			<div class="specification-wrapper">
				<div class="specification-wrapper-content" ref="wrapper">
					<div>
						<div class="specification-header">
							<div class="specification-left">
								<van-image
									class="product-img"
									:src="selectShop.image ? selectShop.image : goodsInfo[goodsThumbName]"
									:style="{ backgroundColor: goodsThumbBackgroundColor }"
									@click="predivImage"
								/>
							</div>
							<div class="specification-right">
								<div class="price-content" :style="{ color: themeColorFn('priceColor') }">
									<text class="sign">¥</text>
									<text class="price" :class="priceCom.length > 16 ? 'price2' : ''">{{ priceCom }}</text>
								</div>
								<div class="inventory" v-if="!hideStock">{{ stockText }}：{{ stockCom }}</div>
								<div class="inventory" v-else></div>
								<div class="choose" v-show="isManyCom">已选：{{ selectArr.join(' ') }}</div>
							</div>
						</div>

						<div class="specification-content">
							<div v-show="isManyCom" class="specification-item" v-for="(item, index1) in goodsInfo[specListName]" :key="index1">
								<div class="item-title">{{ item.name }}</div>
								<div class="item-wrapper">
									<div
										class="item-content"
										v-for="(item_value, index2) in item.list"
										:key="index2"
										:class="[item_value.ishow ? '' : 'noactived', subIndex[index1] == index2 ? 'actived' : '']"
										:style="[
											item_value.ishow ? '' : themeColorFn('disableStyle'),
											item_value.ishow ? themeColorFn('btnStyle') : '',
											subIndex[index1] == index2 ? themeColorFn('activedStyle') : ''
										]"
										@click="skuClick(item_value, index1, index2)"
									>
										{{ item_value.name }}
									</div>
								</div>
							</div>
							<div class="number-box-div">
								<div style="flex: 1;">数量</div>
								<div style="flex: 4;text-align: right;">
									<VkDataInputNumberBox
										:modelValue="selectNum"
										:min="minBuyNum || 1"
										:max="maxBuyNumCom"
										:step="stepBuyNum || 1"
										:step-strictly="stepStrictly"
										:positive-integer="true"
										@change="numChange"
									/>
								</div>
							</div>
						</div>
					</div>
				</div>

				<div class="close" @click="close('close')" v-if="showClose != false"><van-image class="close-item" :src="closeImage"></van-image></div>
			</div>

			<div class="btn-wrapper" v-if="outFoStock || mode == 4">
				<div class="sure" style="color:#ffffff;background-color:#cccccc">{{ noStockText }}</div>
			</div>
			<div class="btn-wrapper" v-else-if="mode == 1">
				<div
					class="sure add-cart"
					style="border-radius:19px 0px 0px 19px;"
					:style="{
						color: themeColorFn('addCartColor'),
						backgroundColor: themeColorFn('addCartBackgroundColor')
					}"
					@click="addCart"
				>
					{{ addCartText }}
				</div>

				<div
					class="sure"
					style="border-radius:0px 19px 19px 0px;"
					:style="{
						color: themeColorFn('buyNowColor'),
						backgroundColor: themeColorFn('buyNowBackgroundColor')
					}"
					@click="buyNow"
				>
					{{ buyNowText }}
				</div>
			</div>
			<div class="btn-wrapper" v-else-if="mode == 2">
				<div
					class="sure add-cart"
					:style="{
						color: themeColorFn('addCartColor'),
						backgroundColor: themeColorFn('addCartBackgroundColor')
					}"
					@click="addCart"
				>
					{{ addCartText }}
				</div>
			</div>
			<div class="btn-wrapper" v-else-if="mode == 3">
				<div
					class="sure"
					:style="{
						color: themeColorFn('buyNowColor'),
						backgroundColor: themeColorFn('buyNowBackgroundColor')
					}"
					@click="buyNow"
				>
					{{ buyNowText }}
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { showImagePreview, showToast } from 'vant';
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import VkDataInputNumberBox from '../vk-data-input-number-box/vk-data-input-number-box.vue'
import BScroll from 'better-scroll'

const props = defineProps({
	// true 组件显示 false 组件隐藏
	value: {
		Type: Boolean,
		default: false
	},
	modelValue: {
		Type: Boolean,
		default: false
	},
	// vk云函数路由模式参数开始-----------------------------------------------------------
	// 商品id
	goodsId: {
		Type: String,
		default: ''
	},
	// vk路由模式框架下的云函数地址
	action: {
		Type: String,
		default: ''
	},
	// vk云函数路由模式参数结束-----------------------------------------------------------
	// 该商品已抢完时的按钮文字
	noStockText: {
		Type: String,
		default: '该商品已抢完'
	},
	// 库存文字
	stockText: {
		Type: String,
		default: '库存'
	},
	// 商品表id的字段名
	goodsIdName: {
		Type: String,
		default: '_id'
	},
	// sku表id的字段名
	skuIdName: {
		Type: String,
		default: '_id'
	},
	// sku_list的字段名
	skuListName: {
		Type: String,
		default: 'sku_list'
	},
	// spec_list的字段名
	specListName: {
		Type: String,
		default: 'spec_list'
	},
	// 库存的字段名 默认 stock
	stockName: {
		Type: String,
		default: 'stock'
	},
	// sku组合路径的字段名
	skuArrName: {
		Type: String,
		default: 'sku_name_arr'
	},
	// 默认单规格时的规格组名称
	defaultSingleSkuName: {
		Type: String,
		default: '默认'
	},
	// 模式 1:都显示  2:只显示购物车 3:只显示立即购买 4:显示缺货按钮 默认 1
	mode: {
		Type: Number,
		default: 1
	},
	// 点击遮罩是否关闭组件 true 关闭 false 不关闭 默认true
	maskCloseAble: {
		Type: Boolean,
		default: true
	},
	// 顶部圆角值
	borderRadius: {
		Type: [String, Number],
		default: 15
	},
	// 商品缩略图字段名(未选择sku时)
	goodsThumbName: {
		Type: [String],
		default: 'goods_thumb'
	},
	// 商品缩略图背景颜色，如#999999
	goodsThumbBackgroundColor: {
		Type: String,
		default: 'transparent'
	},
	// 最小购买数量 默认 1
	minBuyNum: {
		Type: [Number, String],
		default: 1
	},
	// 最大购买数量 默认 100000
	maxBuyNum: {
		Type: [Number, String],
		default: 100000
	},
	// 步进器步长 默认 1
	stepBuyNum: {
		Type: [Number, String],
		default: 1
	},
	// 是否只能输入 step 的倍数
	stepStrictly: {
		Type: Boolean,
		default: false
	},
	// 自定义获取商品信息的函数,支付宝小程序不支持该属性,请使用localdata属性
	customAction: {
		Type: [Function],
		default: null
	},
	// 本地数据源
	localdata: {
		type: Object
	},
	// 价格的字体颜色
	priceColor: {
		Type: String
	},
	// 立即购买按钮的文字
	buyNowText: {
		Type: String,
		default: '立即购买'
	},
	// 立即购买按钮的字体颜色
	buyNowColor: {
		Type: String
	},
	// 立即购买按钮的背景颜色
	buyNowBackgroundColor: {
		Type: String
	},
	// 加入购物车按钮的文字
	addCartText: {
		Type: String,
		default: '加入购物车'
	},
	// 加入购物车按钮的字体颜色
	addCartColor: {
		Type: String
	},
	// 加入购物车按钮的背景颜色
	addCartBackgroundColor: {
		Type: String
	},
	// 不可点击时,按钮的样式
	disableStyle: {
		Type: Object,
		default: null
	},
	// 按钮点击时的样式
	activedStyle: {
		Type: Object,
		default: null
	},
	// 按钮常态的样式
	btnStyle: {
		Type: Object,
		default: null
	},
	// 是否显示右上角关闭按钮
	showClose: {
		Type: Boolean,
		default: true
	},
	// 关闭按钮的图片地址 https://img.alicdn.com/imgextra/i1/121022687/O1CN01ImN0O11VigqwzpLiK_!!121022687.png
	closeImage: {
		Type: String,
		default:
			''
	},
	// 是否隐藏库存显示
	hideStock: {
		Type: Boolean,
		default: false
	},
	// 颜色主题
	theme: {
		Type: String,
		default: 'default'
	},
	// 请求中的提示
	actionTips: {
		Type: String,
		default: '请求中...'
	},
	// 默认选中的SKU
	defaultSelect: {
		Type: Object
	},
	// 是否使用缓存
	useCache: {
		Type: Boolean,
		default: true
	},
	/**
	 * 默认商品,设置该值可快速展示商品
	 * 逻辑: 先展示 defaultGoods 信息,再取数据库,再更新页面(通常为更新库存)
	 */
	defaultGoods: {
		Type: Object
	},
	/**
	 * 金额是否需要除以100
	 * 1:金额会除以100
	 * 0:金额不会除以100
	 */
	amountType: {
		Type: Number,
		default: 1
	},
	// 每次选择完SKU后，购买数量归1，如果有最小购买数量，则设置为最小购买数量
	selectedInit: {
		Type: Boolean,
		default: false
	},
	// 是否开启底部安全区适配，默认true
	safeAreaInsetBottom: {
		Type: Boolean,
		default: false
	},
})

const goodsCache = ref({})
const complete = ref(false) // 组件是否加载完成
const goodsInfo = ref({}) // 商品信息
const isShow = ref(false) // true 显示 false 隐藏
const initKey = ref(true) // 是否需要初始化 true 是 false 否
const shopItemInfo = ref({}) // 存放要和选中的值进行匹配的数据
const selectArr = ref([]) // 存放被选中的值
const subIndex = ref([]) // 是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
const selectShop = ref({}) // 存放最后选中的商品
const selectNum = ref(props.minBuyNum) // 选中数量
const outFoStock = ref(false) // 是否全部sku都缺货
const openTime = ref(0)
const themeColor = reactive({
	// 默认主题
	default: {
		priceColor: 'rgb(254, 86, 10)',
		buyNowColor: '#ffffff',
		buyNowBackgroundColor: 'rgb(254, 86, 10)',
		addCartColor: '#ffffff',
		addCartBackgroundColor: 'rgb(255, 148, 2)',
		btnStyle: {
			color: '#333333',
			borderColor: '#f4f4f4',
			backgroundColor: '#ffffff'
		},
		activedStyle: {
			color: 'rgb(254, 86, 10)',
			borderColor: 'rgb(254, 86, 10)',
			backgroundColor: 'rgba(254,86,10,0.1)'
		},
		disableStyle: {
			color: '#c3c3c3',
			borderColor: '#f6f6f6',
			backgroundColor: '#f6f6f6'
		}
	},
	// 红黑主题
	'red-black': {
		priceColor: 'rgb(255, 68, 68)',
		buyNowColor: '#ffffff',
		buyNowBackgroundColor: 'rgb(255, 68, 68)',
		addCartColor: '#ffffff',
		addCartBackgroundColor: 'rgb(85, 85, 85)',
		activedStyle: {
			color: 'rgb(255, 68, 68)',
			borderColor: 'rgb(255, 68, 68)',
			backgroundColor: 'rgba(255,68,68,0.1)'
		}
	},
	// 黑白主题
	'black-white': {
		priceColor: 'rgb(47, 47, 52)',
		buyNowColor: '#ffffff',
		buyNowBackgroundColor: 'rgb(47, 47, 52)',
		addCartColor: 'rgb(47, 47, 52)',
		addCartBackgroundColor: 'rgb(235, 236, 242)',
		// btnStyle:{
		// 	color:"rgb(47, 47, 52)",
		// 	borderColor:"rgba(235,236,242,0.5)",
		// 	backgroundColor:"rgba(235,236,242,0.5)",
		// },
		activedStyle: {
			color: 'rgb(47, 47, 52)',
			borderColor: 'rgba(47,47,52,0.12)',
			backgroundColor: 'rgba(47,47,52,0.12)'
		}
	},
	// 咖啡色主题
	coffee: {
		priceColor: 'rgb(195, 167, 105)',
		buyNowColor: '#ffffff',
		buyNowBackgroundColor: 'rgb(195, 167, 105)',
		addCartColor: 'rgb(195, 167, 105)',
		addCartBackgroundColor: 'rgb(243, 238, 225)',
		activedStyle: {
			color: 'rgb(195, 167, 105)',
			borderColor: 'rgb(195, 167, 105)',
			backgroundColor: 'rgba(195, 167, 105,0.1)'
		}
	},
	// 浅绿色主题
	green: {
		priceColor: 'rgb(99, 190, 114)',
		buyNowColor: '#ffffff',
		buyNowBackgroundColor: 'rgb(99, 190, 114)',
		addCartColor: 'rgb(99, 190, 114)',
		addCartBackgroundColor: 'rgb(225, 244, 227)',
		activedStyle: {
			color: 'rgb(99, 190, 114)',
			borderColor: 'rgb(99, 190, 114)',
			backgroundColor: 'rgba(99, 190, 114,0.1)'
		}
	}
})

const emit = defineEmits(['update:modelValue', 'input', 'update-goods', 'open', 'close', 'add-cart', 'buy-now','cart','buy','num-change'])

// 滚动数据
const wrapper = ref()
let bscroll = reactive({})

onMounted(async () => {
	if (valueCom) {
		await open()

	}
})

// 初始化
const init = (notAutoClick) => {
	// 清空之前的数据
	selectArr.value = [];
	subIndex.value = [];
	selectShop.value = {};
	selectNum.value = props.minBuyNum;
	outFoStock.value = false;
	shopItemInfo.value = {};
	let specListName = props.specListName;
	goodsInfo.value[specListName].map(item => {
		selectArr.value.push('');
		subIndex.value.push(-1);
	});
	checkItem(); // 计算sku里面规格形成路径
	checkInpath(-1); // 传-1是为了不跳过循环
	if (!notAutoClick) autoClickSku(); // 自动选择sku策略
}

// 使用vk路由模式框架获取商品信息
const findGoodsInfo = (obj = {}) => {
	let { useCache } = obj;
	if (typeof vk == 'undefined') {
		showToast('custom-action必须是function');
		return false;
	}

	let { actionTips } = props;
	let actionTitle = '';
	let actionAoading = false;
	if (actionTips !== 'custom') {
		actionTitle = useCache.value ? '' : '请求中...';
	} else {
		actionAoading = useCache.value ? false : true;
	}
	vk.callFunction({
		url: props.action,
		title: actionTitle,
		loading: actionAoading,
		data: {
			goods_id: props.goodsId
		},
		success(data) {
			updateGoodsInfo(goodsInfo);
			// 更新缓存
			goodsCache.value[props.goodsId] = data.goodsInfo;
			emit('update-goods', data.goodsInfo);
		},
		fail() {
			updateValue(false);
		}
	});
}


// 更新值
const updateValue = (value) => {
	if (value) {
		emit('open', true);
		emit('input', true);
		emit('update:modelValue', true);
	} else {
		emit('input', false);
		emit('close', 'close');
		emit('update:modelValue', false);
	}

	nextTick(() => {
		bscroll = new BScroll(wrapper.value, {
			probeType: 3,
			click: true,
		})


		// 监听滚动
		// bscroll.on('scroll',(position) => {
		// 	console.log('position =', position);
		// });
	})
}

// 更新商品信息(库存、名称、图片)
const updateGoodsInfo = (goodsInformation) => {
	// goodsInfo.sku_list.map((item, index) => {
	// 	item.sku_name_arr = ["20ml/瓶"];
	// });

	let { skuListName } = props;
	if (JSON.stringify(goodsInfo.value) === '{}' || goodsInfo.value[props.goodsIdName] !== goodsInformation[props.goodsIdName]) {
		goodsInfo.value = goodsInformation;
		initKey.value = true;
	} else {
		goodsInfo.value[props.skuListName] = goodsInfo.value[props.skuListName];
	}
	if (initKey.value) {
		initKey.value = false;
		init();
	}
	// 更新选中sku的库存信息
	let select_sku_info = getListItem(goodsInfo.value[props.skuListName], props.skuIdName, selectShop.value[props.skuIdName]);
	Object.assign(selectShop.value, select_sku_info);
	defaultSelectSku();
	complete.value = true;
}

const open = async() => {
	openTime.value = new Date().getTime();
	let findGoodsInfoRun = true;
	let skuListName = props.skuListName;
	// 先获取缓存中的商品信息
	let useCache = false;
	let goodsInfo = goodsCache.value[props.goodsId];
	if (goodsInfo && props.useCache) {
		useCache = true;
		updateGoodsInfo(goodsInfo);
	} else {
		complete.value = false;
	}
	
	if (props.customAction && typeof props.customAction === 'function') {
		try {
			goodsInfo = await customAction({
					useCache,
					goodsId: props.goodsId,
					goodsInfo,
					close: function() {
						setTimeout(function() {
							close();
						}, 500);
					}
				})
				.catch(err => {
					setTimeout(function() {
						close();
					}, 500);
				});
		} catch (err) {
			let { message = '' } = err;
			if (message.indexOf('.catch is not a function') > -1) {
				showToast('custom-action必须返回一个Promise');
				setTimeout(function() {
					close();
				}, 500);
				return false;
			}
		}
		// 更新缓存
		goodsCache.value[props.goodsId] = goodsInfo;
		if (goodsInfo && typeof goodsInfo == 'object' && JSON.stringify(goodsInfo) != '{}') {
			findGoodsInfoRun = false;
			updateGoodsInfo(goodsInfo);
			updateValue(true);
		} else {
			showToast('未获取到商品信息');
			emit('input', false);
			return false;
		}
	} else if (typeof props.localdata !== 'undefined' && props.localdata !== null) {
		goodsInfo = props.localdata;
		if (goodsInfo && typeof goodsInfo == 'object' && JSON.stringify(goodsInfo) != '{}') {
			findGoodsInfoRun = false;
			updateGoodsInfo(goodsInfo);
			updateValue(true);
		} else {
			showToast('未获取到商品信息');
			emit('input', false);
			return false;
		}
	} else {
		if (findGoodsInfoRun) findGoodsInfo({ useCache });
	}
}

// 监听 - 弹出层收起
const close = (s) => {
	if (new Date().getTime() - openTime.value < 400) {
		return false;
	}
	if (s == 'mask') {
		if (props.maskCloseAble !== false) {
			emit('input', false);
			emit('close', 'mask');
			emit('update:modelValue', false);
		}
	} else {
		emit('input', false);
		emit('close', 'close');
		emit('update:modelValue', false);
	}

	bscroll.scrollTo(0, 0, 500)
}


// sku按钮的点击事件
const skuClick = (value, index1, index2) => {
	if (value.ishow) {
		if (selectArr.value[index1] != value.name) {
			selectArr.value[index1] = value.name
			subIndex.value[index1] = index2
		} else {
			selectArr.value[index1] = ''
			subIndex.value[index1] = -1
		}

		checkInpath(index1);
		// 如果全部选完
		checkSelectShop();
	}
}


// 检测是否已经选完sku
const checkSelectShop = () => {
	// 如果全部选完
	if (selectArr.value.every(item => item != '')) {
		selectShop.value = shopItemInfo.value[getArrayToSting(selectArr.value)];
		let stock = selectShop.value[props.stockName];
		if (typeof stock !== 'undefined' && selectNum.value > stock) {
			selectNum.value = stock;
		}
		if (selectNum.value > props.maxBuyNum) {
			selectNum.value =  props.maxBuyNum;
		}
		if (selectNum.value < props.minBuyNum) {
			selectNum.value = props.minBuyNum;
		}
		if (props.selectedInit) {
			selectNum.value = props.minBuyNum || 1;
		}
	} else {
		selectShop.value = {};
	}
}

// 检查路径
const checkInpath = (clickIndex) => {
	let specListName = props.specListName;
	//console.time('筛选可选路径需要的时间是');
	//循环所有属性判断哪些属性可选
	//当前选中的兄弟节点和已选中属性不需要循环
	let specList = goodsInfo.value[specListName];
	for (let i = 0, len = specList.length; i < len; i++) {
		if (i == clickIndex) {
			continue;
		}
		let len2 = specList[i].list.length;
		for (let j = 0; j < len2; j++) {
			if (subIndex.value[i] != -1 && j == subIndex.value[i]) {
				continue;
			}
			let choosed_copy = [...selectArr.value];
			choosed_copy[i] = specList[i].list[j].name
			let choosed_copy2 = choosed_copy.filter(item => item !== '' && typeof item !== 'undefined');
			if (shopItemInfo.value.hasOwnProperty(getArrayToSting(choosed_copy2))) {
				specList[i].list[j].ishow = true;
			} else {
				specList[i].list[j].ishow = false;
			}
		}
	}
	goodsInfo.value[specListName] = specList
	// console.timeEnd('筛选可选路径需要的时间是');
}

// 计算sku里面规格形成路径
const checkItem = () => {
	// console.time('计算有多小种可选路径需要的时间是');
	let { stockName } = props;
	let skuListName = props.skuListName;
	// 去除库存小于等于0的商品sku
	let originalSkuList = goodsInfo.value[skuListName];
	let skuList = [];
	let stockNum = 0;
	originalSkuList.map((skuItem, index) => {
		if (skuItem[stockName] > 0) {
			skuList.push(skuItem);
			stockNum += skuItem[stockName];
		}
	});
	if (stockNum <= 0) {
		outFoStock.value = true;
	}
	// 计算有多小种可选路径
	let result = skuList.reduce(
		(arrs, items) => {
			return arrs.concat(
				items[props.skuArrName].reduce(
					(arr, item) => {
						return arr.concat(
							arr.map(item2 => {
								// 利用对象属性的唯一性实现二维数组去重
								//console.log(1,that.shopItemInfo,that.getArrayToSting([...item2, item]),item2,item,items);
								if (!shopItemInfo.value.hasOwnProperty(getArrayToSting([...item2, item]))) {
									shopItemInfo.value[getArrayToSting([...item2, item])] = items;
								}
								return [...item2, item];
							})
						);
					},
					[[]]
				)
			);
		},
		[[]]
	);
	// console.timeEnd('计算有多小种可选路径需要的时间是');
}

const getArrayToSting = (arr) => {
	let str = '';
	arr.map((item, index) => {
		item = item.replace(/\./g, '。');
		if (index == 0) {
			str += item;
		} else {
			str += ',' + item;
		}
	});
	return str;
}

const clickTim = ref(0)
// 检测sku选项是否已全部选完,且有库存
const checkSelectComplete = (obj = {}) => {
	let clickTime = new Date().getTime();
	if (clickTim.value && clickTime - clickTim.value < 400) {
		return false;
	}
	clickTim.value = clickTime;
	let { stockText, stockName, skuIdName } = props;
	if (!selectShop.value || !selectShop.value[skuIdName]) {
		showToast('请先选择对应规格');
		return false;
	}
	if (selectNum.value <= 0) {
		showToast('购买数量必须>0');
		return false;
	}
	// 判断库存
	if (selectNum.value > selectShop.value[stockName]) {
		showToast(stockText + '不足');
		return false;
	}
	if (typeof obj.success == 'function') obj.success(selectShop.value);
}

// 加入购物车
const addCart = () => {
	checkSelectComplete({
		success: function(selectShop) {
			selectShop.buy_num = selectNum.value;
			emit('add-cart', selectShop);
			emit('cart', selectShop);

			bscroll.scrollTo(0, 0, 500)
			// setTimeout(function() {
			// 	that.init();
			// }, 300);
		}
	});
}

// 立即购买
const buyNow = () => {
	checkSelectComplete({
		success: function(selectShop) {
			selectShop.buy_num = selectNum.value;
			emit('buy-now', selectShop);
			emit('buy', selectShop);

			bscroll.scrollTo(0, 0, 500)
		}
	});
}

// 获取对象数组中的某一个item,根据指定的键值
const getListItem = (list, key, value) => {
	let item;
	for (let i in list) {
		if (typeof value == 'object') {
			if (JSON.stringify(list[i][key]) === JSON.stringify(value)) {
				item = list[i];
				break;
			}
		} else {
			if (list[i][key] === value) {
				item = list[i];
				break;
			}
		}
	}
	return item;
}

const getListIndex = (list, key, value) => {
	let index = -1;
	for (let i = 0; i < list.length; i++) {
		if (list[i][key] === value) {
			index = i;
			break;
		}
	}
	return index;
}

// 自动选择sku前提是只有一组sku,默认自动选择最前面的有库存的sku
const autoClickSku = () => {
	let { stockName } = props;
	let skuList = goodsInfo.value[props.skuListName];
	let specListArr = goodsInfo.value[props.specListName];
	if (specListArr.length == 1) {
		let specList = specListArr[0].list;
		for (let i = 0; i < specList.length; i++) {
			let sku = getListItem(skuList, props.skuArrName, [specList[i].name]);
			if (sku && sku[stockName] > 0) {
				skuClick(specList[i], 0, i);
				break;
			}
		}
	}
}

// 主题颜色
const themeColorFn = (name) => {
	let color = props[name] ? props[name] : themeColor[props.theme][name];
	return color
}

// 默认选择sku
const defaultSelectSku = () => {
	let { defaultSelect } = props;
	if (defaultSelect && defaultSelect.sku && defaultSelect.sku.length > 0) {
		selectSku(defaultSelect);
	}
}

// 选择sku
const selectSku = (obj = {}) => {
	let { sku: skuArr, num: selectNumber } = obj;
	let specListArr = goodsInfo.value[props.specListName];
	if (skuArr && specListArr.length === skuArr.length) {
		// 先清空
		let skuClickArr = [];
		let clickKey = true;
		for (let index = 0; index < skuArr.length; index++) {
			let skuName = skuArr[index];
			let specList = specListArr[index].list;
			let index1 = index;
			let index2 = getListIndex(specList, 'name', skuName);
			if (index2 == -1) {
				clickKey = false;
				break;
			}
			skuClickArr.push({
				spec: specList[index2],
				index1: index1,
				index2: index2
			});
		}
		if (clickKey) {
			init(true);
			skuClickArr.map(item => {
				skuClick(item.spec, item.index1, item.index2);
			});
		}
	}
	if (selectNumber > 0) selectNum.value = selectNumber;
}

// 价格过滤
const priceFilter = (n = 0) => {
	if (typeof n == 'string') {
		n = parseFloat(n);
	}
	if (props.amountType === 0) {
		return n.toFixed(2);
	} else {
		return (n / 100).toFixed(2);
	}
}

// 加入商品缓存
const pushGoodsCache = (goodsInfo) => {
	goodsCache.value[goodsInfo.value[props.goodsIdName]] = goodsInfo;
}

// 图片预览
const predivImage = () => {
	let src = selectShop.value.image ? selectShop.value.image : goodsInfo.value[props.goodsThumbName];
	if (src) {
		showImagePreview({images: [src]})
	}
}

// 获取最大的库存
const getMaxStock = () => {
	let maxStock = 0;
	let { skuListName, stockName } = props;
	if (selectShop.value[stockName]) {
		maxStock = selectShop.value[stockName];
	} else {
		let skuList = goodsInfo.value[skuListName];
		if (skuList && skuList.length > 0) {
			let valueArr = [];
			skuList.map((skuItem, index) => {
				valueArr.push(skuItem[stockName]);
			});
			let max = Math.max(...valueArr);
			maxStock = max;
		}
	}
	return maxStock;
}

// 修改数量
const numChange = (e) => {
	selectNum.value = e.value
	emit("num-change", e.value);
}


// 计算属性
const valueCom = computed(() =>{
	return props.modelValue
})

// 最大购买数量
const maxBuyNumCom = computed(() =>{
	let maxStock = getMaxStock();
	let max = props.maxBuyNum || 100000;
	// 最大购买量不能超过当前商品的库存
	if (max > maxStock) {
		max = maxStock;
	}
	return max;
})

// 是否是多规格
const isManyCom = computed(() =>{
	let { defaultSingleSkuName, specListName } = props;
	let isMany = true;
	if (
		goodsInfo.value[specListName] &&
		goodsInfo.value[specListName].length === 1 &&
		goodsInfo.value[specListName][0].list.length === 1 &&
		goodsInfo.value[specListName][0].name === defaultSingleSkuName
	) {
		isMany = false;
	}
	return isMany;
})

// 默认价格区间计算
const priceCom = computed(() =>{
	let str = '';
	let { skuListName, skuIdName } = props;
	if (selectShop.value[skuIdName]) {
		str = priceFilter(selectShop.value.price);
	} else {
		let skuList = goodsInfo.value[skuListName];
		if (skuList && skuList.length > 0) {
			let valueArr = [];
			skuList.map((skuItem, index) => {
				valueArr.push(skuItem.price);
			});
			let min = priceFilter(Math.min(...valueArr));
			let max = priceFilter(Math.max(...valueArr));
			if (min === max) {
				str = min + '';
			} else {
				str = `${min} - ${max}`;
			}
		}
	}
	return str;
})

// 库存显示
const stockCom = computed(() =>{
	let str = '';
	let { skuListName, stockName } = props;
	if (selectShop.value[stockName]) {
		str = selectShop.value[stockName];
	} else {
		let skuList = goodsInfo.value[skuListName];
		if (skuList && skuList.length > 0) {
			let valueArr = [];
			skuList.map((skuItem) => {
				valueArr.push(skuItem[stockName]);
			});
			let min = Math.min(...valueArr);
			let max = Math.max(...valueArr);
			if (min === max) {
				str = min;
			} else {
				str = `${min} - ${max}`;
			}
		}
	}
	return str;
})


watch(valueCom, (newVal, oldValue) => {
	if (newVal) {
		open();
	}
})

// 导出
defineExpose({
    selectArr,
	selectSku
})

// 监听默认商品
// watch(props.defaultGoods, (newVal, oldValue) => {
// 	let { goodsIdName } = props;
// 	if (typeof newVal === 'object' && newVal && newVal[goodsIdName] && !goodsCache.value[newVal[goodsIdName]]) {
// 		pushGoodsCache(newVal);
// 	}
// },{
// 	// 初始化的时候也会执行
// 	immediate: true,
// })
</script>

<style lang="scss" scoped>
/*  sku弹出层 */
.vk-data-goods-sku-popup {
	position: fixed;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	z-index: 990;
	overflow: hidden;
	&.show {
		display: block;

		.mask {
			animation: showPopup 0.2s linear both;
		}

		.layer {
			animation: showLayer 0.2s linear both;
		}
	}

	&.hide {
		.mask {
			animation: hidePopup 0.2s linear both;
		}

		.layer {
			animation: hideLayer 0.2s linear both;
		}
	}

	&.none {
		display: none;
	}
	.mask {
		position: fixed;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
		background-color: rgba(0, 0, 0, 0.3);
	}
	.layer {
		display: flex;
		width: 100%;
		flex-direction: column;
		position: fixed;
		z-index: 99;
		bottom: 0;
		border-radius: 5px 5px 0 0;
		background-color: #fff;

		.specification-wrapper {
			width: 100%;
			padding: 15px 13px;
			box-sizing: border-box;
			position: relative;
			// height: 400px;
			.specification-wrapper-content {
				width: 100%;
				overflow: hidden;
				// height: 450px;
				max-height: 370px;
				min-height: 150px;
				// height: 100%;
				&::-webkit-scrollbar {
					/*隐藏滚轮*/
					display: none;
				}

				.specification-header {
					width: 100%;
					display: flex;
					flex-direction: row;
					position: relative;
					margin-bottom: 20px;

					.specification-left {
						width: 90px;
						height: 90px;
						flex: 0 0 90px;

						.product-img {
							width: 90px;
							height: 90px;
						}
					}

					.specification-right {
						flex: 1;
						padding: 0 18px 0 14px;
						box-sizing: border-box;
						display: flex;
						flex-direction: column;
						justify-content: flex-end;
						font-weight: 500;

						.price-content {
							color: #fe560a;
							margin-bottom: 10px;

							.sign {
								font-size: 14px;
							}

							.price {
								margin-left: 2px;
								font-size: 24px;
							}
							.price2 {
								margin-left: 2px;
								font-size: 18px;
							}
						}

						.inventory {
							font-size: 12px;
							color: #999999;
							margin-bottom: 7px;
						}

						.choose {
							font-size: 14px;
							color: #333333;
						}
					}
				}

				.specification-content {
					font-weight: 500;

					.specification-item {
						margin-bottom: 20px;

						&:last-child {
							margin-bottom: 0;
						}

						.item-title {
							margin-bottom: 10px;
							font-size: 14px;
							color: #999999;
						}

						.item-wrapper {
							display: flex;
							flex-direction: row;
							flex-flow: wrap;

							.item-content {
								display: inline-block;
								padding: 5px 18px;
								font-size: 12px;
								border-radius: 5px;
								background-color: #ffffff;
								color: #333333;
								margin-right: 10px;
								margin-bottom: 8px;
								border: 1px solid #f4f4f4;
								box-sizing: border-box;
								&.actived {
									border-color: #fe560a;
									color: #fe560a;
								}

								&.noactived {
									background-color: #f6f6f6;
									border-color: #f6f6f6;
									color: #c3c3c3;
								}
							}
						}
					}
					.number-box-div {
						display: flex;
						padding-top: 8px;
					}
				}
			}
			.close {
				position: absolute;
				top: 15px;
				right: 13px;
				width: 25px;
				height: 25px;
				text-align: center;
				line-height: 25px;
				.close-item {
					width: 25px;
					height: 25px;
				}
			}
		}
		.btn-wrapper {
			display: flex;
			width: 100%;
			height: 60px;
			flex: 0 0 60px;
			align-items: center;
			justify-content: space-between;
			padding: 0 13px;
			box-sizing: border-box;
			.layer-btn {
				width: 168px;
				height: 38px;
				border-radius: 19px;
				color: #fff;
				line-height: 38px;
				text-align: center;
				font-weight: 500;
				font-size: 14px;

				&.add-cart {
					background: #ffbe46;
				}

				&.buy {
					background: #fe560a;
				}
			}
			.sure {
				width: 349px;
				height: 34px;
				border-radius: 19px;
				color: #fff;
				line-height: 34px;
				text-align: center;
				font-weight: 500;
				font-size: 14px;
				background: #fe560a;
			}
			.sure.add-cart {
				background: #ff9402;
			}
		}
		.btn-wrapper.safe-area-inset-bottom{
			padding-bottom: 0;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
		}
	}

	@keyframes showPopup {
		0% {
			opacity: 0;
		}

		100% {
			opacity: 1;
		}
	}

	@keyframes hidePopup {
		0% {
			opacity: 1;
		}

		100% {
			opacity: 0;
		}
	}

	@keyframes showLayer {
		0% {
			transform: translateY(120%);
		}

		100% {
			transform: translateY(0%);
		}
	}

	@keyframes hideLayer {
		0% {
			transform: translateY(0);
		}

		100% {
			transform: translateY(120%);
		}
	}
}
</style>
